package admin

import (
	"gitee.com/jikey/elk-blog/pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/nleeper/goment"
	"github.com/sirupsen/logrus"
	"os"
)

// UploadImage 上传图片
func UploadImage(c *gin.Context) {
	file, err := c.FormFile("file")
	data := make(map[string]interface{})

	if err != nil {
		response.Fail(c, 201, "上传图片出错了")
		return
	}

	// 增加时间文件不易重复，且可追溯
	g, _ := goment.New()
	today := g.Format("YYYYMMDD")
	savePath := "public/uploads/blog/"
	path := savePath + today

	// 如果没有path文件目录就创建一个
	if _, err := os.Stat(path); err != nil {
		if !os.IsExist(err) {
			err2 := os.MkdirAll(path, os.ModePerm)
			if err2 != nil {
				return
			}

			logrus.Info("创建文件夹:" + path)
		}
	}

	filePath := path + "/" + file.Filename
	// 上传到指定目录
	err = c.SaveUploadedFile(file, filePath)

	if err != nil {
		response.Fail(c, 201, err.Error())
		return
	}

	data["path"] = filePath

	response.Success(c, data)
	return
}
